import { isObject } from '@/utils'

export const FormMixin = {
  props: {
    value: { type: Object, default: () => ({}) },
    cfg: { type: Object, default: () => ({}) }
  },
  data() {
    return {
      formInitVals: {},
      form: {},
      prevData: ''
    }
  },
  computed: {
    innerValue: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  watch: {
    innerValue: {
      deep: true,
      immediate: true,
      handler(val) {
        const cfg = this.cfg || {}
        const data = val || {}
        const str = JSON.stringify(data)
        if (str === this.prevData) return
        this.prevData = str

        // 配置的默认值
        let defVal = {}
        try {
          const defJson = cfg.defaultJson && JSON.parse(cfg.defaultJson)
          if (isObject(defJson)) defVal = defJson
        } catch (err) {
          console.log('parse defaultJson', err)
        }

        const form = JSON.parse(JSON.stringify(this.formInitVals))
        Object.keys(form).map(k => {
          if (typeof data[k] !== 'undefined') return (form[k] = data[k])
          if (typeof defVal[k] !== 'undefined') return (form[k] = defVal[k])
          // 初始无数据时，chkitemCode 等字段可取自配置
          if (typeof cfg[k] !== 'undefined') return (form[k] = cfg[k])
        })
        this.form = form
        this.innerValue = form
      }
    }
  },
  methods: {
    async validate() {
      const valid = await this.$refs.form.validate().catch(() => false)
      if (!valid) return false
      this.innerValue = this.form
      return true
    }
  }
}

export default FormMixin
